import org.junit.Test;

import java.util.*;

/**
 * @description:集合Map的使用
 * @author:Mr.Cat
 * @create:2021-10-30 14:50
 **/
public class MapTest {

    @Test
    public void test1() {
        Map map = new HashMap();

        //测试HashMap与Hashtable能不能存储null;
        //map = new Hashtable();
        map.put("李雄", "男");
        map.put(null, 123);
        System.out.println(map);

    }

    @Test
    public void test2() {
        Map map = new HashMap();

        //添加
        map.put("AA", 123);
        map.put(45, 123);
        map.put("BB", 56);

        //修改
        map.put("AA", 87);
        System.out.println(map);

        Map map1 = new HashMap();
        map1.put("CC", 123);
        map1.put("DD", 123);

        map.putAll(map1);
        System.out.println(map);

        //移除元素
        map.remove("CC");
        System.out.println(map);

        //清空数据
        map.clear();
        System.out.println(map.size());
    }


    /*
    元视图的使用
    Set keySet():返回所有key构成的Collection集合
    Collection values（）：返回所有value构成的Collection集合
    Set entrySet（）：返回所有key-value对构成的Set集合
     */
    @Test
    public void test3() {
        Map map = new HashMap();

        map.put("AA", 123);
        map.put(45, 123);
        map.put("BB", 56);

        //遍历所有的key集合：keySet（）
        Set set = map.keySet();

        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        System.out.println();
        //遍历所有的value集：values();
        Collection values = map.values();
        for (Object obj : values) {
            System.out.println(obj);
        }

        System.out.println();
        //遍历所有的entry(key-value)
        //方式一：entrySet()
        Set entrySet = map.entrySet();
        Iterator iterator1 = entrySet.iterator();
        while (iterator1.hasNext()) {
            //System.out.println(iterator1.next());
            Object obj = iterator1.next();
            //entrySet集合中的元素都是entry
            Map.Entry entry = (Map.Entry) obj;

            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
        System.out.println();
        //方式二:
        Set keySet = map.keySet();
        Iterator iterator2 = keySet.iterator();
        while (iterator2.hasNext()) {
            //System.out.println(iterator2.next());
            Object key = iterator2.next();
            Object value = map.get(key);
            System.out.println(key + "===" + value);
        }
    }
}

